import type { Action } from 'element-plus'
import type { TableColumnProps } from './components'
import type { ApplicationModel } from '@/types/modules/application-models'

import {
  deleteApplicationModel,
  loadApplicationModelList,
  loadModelPointTreeList,
  // loadApplicationModelTreeList,
  loadTreeList,
  loadTimeTypeList as _loadTimeTypeList,
} from '@/api/modules/applicationModel'
import type { STORAGE_MODES } from '@/enum/modules/indicator'
import { STORAGE_MODES_OPTIONS } from '@/mixins/StatisticalIndicators/MixinStatisticalIndicators'

/** 模型 */
export function useModelLists() {
  const [loading, setLoading] = useState(true)
  const [childrenLoading, setChildrenLoading]
    = useState(false)
  const [lists, setLists] = useShallowState<
    ApplicationModel[]
  >([])
  const [children, setChildren] = useShallowState<
    ApplicationModel[]
  >([])
  const columns: TableColumnProps[] = shallowReactive([
    { label: '应用模型名称', prop: 'name' },
    { label: '应用模型编码', prop: 'code' },
  ])
  const timeTypeList = shallowRef<{ label: string, value: STORAGE_MODES }[]>([])

  async function getLists() {
    setLoading(true)
    try {
      const { data } = await loadApplicationModelList()
      setLists(data as ApplicationModel[])
    }
    finally {
      setLoading(false)
    }
  }

  async function getChildrenById(id: number) {
    setChildrenLoading(true)
    try {
      const { data } = await loadModelPointTreeList(id)
      setChildren(data as ApplicationModel[])
    }
    finally {
      setChildrenLoading(false)
    }
  }

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确定要删除该模型（或节点）吗？',
      '操作提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }

  async function deleteModelOne(id: number) {
    const action: Action = await confirmDel().catch(e => e)
    if (action === 'confirm') {
      try {
        await deleteApplicationModel(id)
      }
      catch (e) {}
      setLists(unref(lists).filter(item => item.id !== id))
      ElMessage.success('删除成功')
    }
  }

  async function deleteNodeOne(id: number) {
    const action: Action = await confirmDel().catch(e => e)
    if (action === 'confirm') {
      const recursiveFilter = (
        array: ApplicationModel[],
      ): ApplicationModel[] => {
        return array.filter((item) => {
          if (item.id === id) {
            return false
          }
          if (item.children) {
            item.children = recursiveFilter(item.children)
          }
          return true
        })
      }
      try {
        await deleteApplicationModel(id)
      }
      catch (e) {}
      setChildren(recursiveFilter(unref(children)))
      ElMessage.success('删除成功')
    }
  }

  async function getIndicatorsTopologicalGraph(
    timeType: STORAGE_MODES,
    modelId: number,
  ) {
    return await loadTreeList(
      timeType,
      modelId,
    )
  }

  const router = useRouter()
  function toApplicationModels() {
    router.push({
      path: '/application-models',
    })
  }
  function toApplicationModelConfigs() {
    router.push({
      path: '/application-model-configs',
    })
  }

  async function loadTimeTypeList(mId: number) {
    const { data = [] } = await _loadTimeTypeList(mId)
    timeTypeList.value = STORAGE_MODES_OPTIONS.filter(item => data.includes(item.value))
  }

  return {
    loading,
    childrenLoading,
    columns,
    /** 应用模型列表 */
    lists,
    children,
    timeTypeList,
    setChildren,
    setLoading,
    setChildrenLoading,
    /** 获取应用模型列表 */
    getLists,
    getChildrenById,
    /** 删除模型 */
    deleteModelOne,
    /** 删除节点 */
    deleteNodeOne,
    /** 获取指标拓扑图 */
    getIndicatorsTopologicalGraph,

    /** 路由跳转模型管理页面 */
    toApplicationModels,
    /** 路由跳转模型配置页面 */
    toApplicationModelConfigs,
    /** 查询模型对应的时间类型 */
    loadTimeTypeList,
  }
}
